package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sessionFactory;

    //静态代码块，保证这段代码只会执行一次！
    static{
        try {
            //2.1 读取核心配置文件
            InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");

            //2.2 构建构建器
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

            //2.3 得到工厂
            sessionFactory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession
     * @return
     */
    public static  SqlSession openSession(){
        //2.4 问工厂要SqlSession对象
        return sessionFactory.openSession();
    }

}
